<?php

use app\assets\ApiAsset;
use app\assets\LayerAsset;
use app\assets\TableAsset;
use app\models\Card;
use app\models\CardAttr;
use app\models\CardAttrValue;
use app\models\CardBasic;
use app\models\KeyMap;
use app\models\Package;
use app\models\UserPackage;
use app\widgets\LinkPager;
use app\widgets\ManagerTableOp;
use app\widgets\SortColumnLink;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;

/**
 * @var $this yii\web\View
 * @var $user app\models\User
 * @var $attrList app\models\CardAttr[] 需要在列表中显示的属性列表
 * @var $cardList app\models\Card[]
 * @var $pagination yii\data\Pagination
 */

ApiAsset::register($this);
LayerAsset::register($this);
TableAsset::register($this);

$this->title = '卡列表';
$this->params['breadcrumbs'][] = '物联网卡管理';
$this->params['breadcrumbs'][] = $this->title;
?>
<?php echo Html::beginForm('?', 'get', ['class'=>'form-inline']);?>
<div class="form-group">
    <label for="search_status" class="sr-only">状态</label>
    <?php echo Html::dropDownList('search_status', Yii::$app->request->get('search_status'), KeyMap::getValues('card_status'), ['id' => 'search_status', 'class' => 'form-control', 'prompt' => '搜索状态']);?>
</div>
<div class="form-group">
    <label for="search_iccid" class="sr-only">ICCID</label>
    <?php echo Html::textInput('search_iccid', Yii::$app->request->get('search_iccid'), ['id'=>'search_iccid', 'class'=>'form-control', 'placeholder'=>'ICCID', 'style' => 'min-width:180px;']);?>
</div>
<div class="form-group">
    <label for="search_msisdn" class="sr-only">MSISDN</label>
    <?php echo Html::textInput('search_msisdn', Yii::$app->request->get('search_msisdn'), ['id'=>'search_msisdn', 'class'=>'form-control', 'placeholder'=>'MSISDN', 'style' => 'width:120px;']);?>
</div>
<div class="form-group">
    <?php echo Html::checkbox('search_overload', Yii::$app->request->get('search_overload') == 1, ['id' => 'search_overload', 'value' => 1]);?>
        <label for="search_overload">超套卡</label>
</div>
<div class="form-group">
    <label for="search_package_id" class="sr-only">套餐</label>
    <?php echo Html::dropDownList('search_package_id', Yii::$app->request->get('search_package_id'), ArrayHelper::map(UserPackage::find()->andWhere(['uid' => $user->id])->all(), 'package_id', 'package.name'), ['id' => 'search_package_id', 'class' => 'form-control', 'prompt' => '搜索套餐']);?>
</div>
<?php /** @var CardAttr $cardAttr */
foreach (CardAttr::find()->andWhere(['uid' => Yii::$app->user->id, 'status' => CardAttr::STATUS_OK])->each() as $cardAttr) {
    $searchAttr = Yii::$app->request->get('search_attr');?>
    <div class="form-group">
        <label for="search_attr_<?php echo $cardAttr->id; ?>" class="sr-only"><?php echo Html::encode($cardAttr->name);?></label>
        <?php echo Html::textInput('search_attr[' . $cardAttr->id . ']', !isset($searchAttr[$cardAttr->id]) ? '' : $searchAttr[$cardAttr->id], ['id' => 'search_attr_' . $cardAttr->id, 'class' => 'form-control', 'placeholder' => Html::encode($cardAttr->name), 'style' => 'max-width:100px;']);?>
    </div>
<?php }?>
<div class="form-group">
    <button class="btn btn-primary btn-sm">搜索</button>
    <a href="<?php echo Url::current(['export'=>'excel']);?>">导出Excel</a>
    <a href="<?php echo Url::current(['export'=>'csv']);?>">导出CSV</a>
</div>
<br />
<div class="form-group">
    <a href="<?php echo Url::current(['search_status' => null]);?>" class="btn btn-info btn-sm">全部</a>
    <?php foreach (KeyMap::getValues('card_status') as $status => $statusStr) {?>
        <a href="<?php echo Url::current(['search_status' => $status]);?>" class="btn btn-info btn-sm"><?php echo $statusStr;?></a>
    <?php }?>
</div>
<?php echo Html::endForm();?>
<table class="table table-striped table-bordered table-hover">
    <thead>
    <tr>
        <th class="center">
            <label class="pos-rel">
                <input type="checkbox" class="ace" />
                <span class="lbl"><?php echo SortColumnLink::widget(['txt' => '编号', 'name' => 'card.id']);?></span>
            </label>
        </th>
        <th><?php echo SortColumnLink::widget(['txt' => 'ICCID', 'name' => 'card.iccid']);?>/<?php echo SortColumnLink::widget(['txt' => 'MSISDN', 'name' => 'card.msisdn']);?></th>
        <th>套餐/<?php echo SortColumnLink::widget(['txt' => '流量用量', 'name' => 'card.data']);?></th>
        <th><abbr title="套餐有效期&#13;开始时间&#13;结束时间"><?php echo SortColumnLink::widget(['txt' => '套餐有效期', 'name' => 'card.term_end_time']);?></abbr></th>
        <th>短信/语音用量</th>
        <th>状态</th>
        <th>刷新/控制</th>
        <th>激活时间/<?php echo SortColumnLink::widget(['txt' => '刷新时间', 'name' => 'card.refresh_time']);?></th>
        <?php foreach ($attrList as $attr) {?>
            <th><?php echo Html::encode($attr->name);?></th>
        <?php }?>
        <?php if (!empty($attrList)) {?>
            <th><?php echo SortColumnLink::widget(['txt' => '属性更新时间', 'name' => 'card.attr_update_time']);?></th>
        <?php }?>
        <th>操作</th>
    </tr>
    </thead>

    <tbody>
    <?php foreach ($cardList as $card) {
        $cardBasic = CardBasic::findOne(['card_id' => $card->id]);?>
        <tr>
            <td class="center"><label class="pos-rel"><input type="checkbox" class="ace" value="<?php echo $card->id;?>" /><span class="lbl"><?php echo $card->id;?></span></label></td>
            <td><?php echo empty($card->iccid) ? '----' : Html::encode($card->iccid);
                echo '<br />';
                echo empty($card->msisdn) ? '----' : Html::encode($card->msisdn);?></td>
            <td><?php if (empty($card->package_id)) {
                    echo '<i>没有设置</i>';
                } else {
                    echo Html::encode($card->package->name);
                    echo '（', Yii::$app->formatter->asShortSize($card->data), '/ ', Yii::$app->formatter->asShortSize($card->package->data), '）';
                    $dataPercent = $card->package->data == 0 ? 100 : $card->data * 100 / $card->package->data;?>
                    <div class="progress" style="margin-top: 5px; margin-bottom: 2px; height:10px;">
                        <div class="progress-bar progress-bar-<?php echo $dataPercent < 80 ? 'success' : ($dataPercent < 100 ? 'warning' : 'danger');?> progress-bar-striped" role="progressbar" aria-valuenow="<?php echo $card->data;?>" aria-valuemin="0" aria-valuemax="<?php echo $card->package->data;?>" style="width: <?php echo $dataPercent;?>%"></div>
                    </div>
                <?php }?></td>
            <td><?php if (!empty($card->term_length_unit)) {
                    echo $card->term_length, '(', KeyMap::getValue('card_term_length_unit', $card->term_length_unit), ')<br />';
                    if (empty($card->active_time)) {
                        echo '----';
                    } else {
                        echo Yii::$app->formatter->asDate($card->active_time);
                    }
                    echo '<br />';
                    if (empty($card->term_end_time)) {
                        echo '----';
                    } else {
                        if (time() + 30 * 86400 > $card->term_end_time) {
                            echo '<span class="text-danger" title="30天内到期"><i class="fa fa-exclamation-triangle"></i><strong>', Yii::$app->formatter->asDate($card->term_end_time), '</strong></span>';
                        } else {
                            echo Yii::$app->formatter->asDate($card->term_end_time);
                        }
                    }
                }?></td>
            <td>已用<?php echo $card->sms;?>条<br />
                已用<?php echo $card->voice;?>分钟</td>
            <td><?php echo KeyMap::getValue('card_status', $card->status);?><br />
                <?php if ($card->on_off != 1) {
                    echo '未知或离线';
                } else {
                    echo '在线：', $card->ip;
                }?><br /></td>
            <td>
                <div class="btn-group">
                    <button type="button" class="btn btn-xs btn-info" onclick="refreshCard(<?php echo $card->id;?>, this)"><i class="fa fa-refresh"></i></button>
                    <button type="button" class="btn btn-xs btn-warning" onclick="restartCard(<?php echo $card->id;?>)" title="强制设备断开网络，使其重新注册。"><i class="fa fa-repeat"></i></button>
                    <button type="button" class="btn btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" title="设置状态">
                        <i class="ace-icon fa fa-magic"></i>
                    </button>
                    <ul class="dropdown-menu">
                        <?php foreach (Card::STATUS_TRANSFORM_MAP[$card->status] as $status) {?>
                            <li><a href="javascript:void(0)" onclick="setCardStatus(<?php echo $card->id, ', ', $status;?>)"><?php echo KeyMap::getValue('card_status', $status);?></a></li>
                        <?php }?>
                    </ul>
                </div>
            </td>
            <td><?php echo empty($card->active_time) ? '----' : Yii::$app->formatter->asDatetime($card->active_time);
                echo '<br />';
                echo empty($card->refresh_time) ? '----' : Yii::$app->formatter->asDatetime($card->refresh_time);?></td>
            <?php foreach ($attrList as $attr) {?>
                <td style="white-space: pre;"><?php $attrValue = CardAttrValue::findOne(['uid' => $card->uid, 'attr_id' => $attr->id, 'card_id' => $card->id]);
                    if (!empty($attrValue)) {
                        echo Html::encode($attr->getHtml($attrValue->value));
                    }?></td>
            <?php }?>
            <?php if (!empty($attrList)) {?>
                <td><?php echo Yii::$app->formatter->asDatetime($card->attr_update_time);?></td>
            <?php }?>
            <td><?php echo ManagerTableOp::widget(['items' => [
                    ['icon' => 'fa fa-info-circle', 'href' => Url::to(['/user/card/view', 'id' => $card->id]), 'btn_class' => 'btn btn-xs btn-default', 'tip' => '详情'],
                    ['icon' => 'fa fa-pencil', 'href' => Url::to(['/user/card/edit', 'id' => $card->id]), 'btn_class' => 'btn btn-xs btn-success', 'tip' => '修改', 'color' => 'green'],
                    ['icon' => 'fa fa-envelope-o', 'onclick' => 'showSms(\'' . $card->msisdn . '\', \'' . $card->sms_ignore_sign . '\')', 'btn_class' => 'btn btn-xs btn-info', 'tip' => '短信', 'color' => 'blue'],
                ]]);?></td>
        </tr>
    <?php }?>
    </tbody>
</table>
<?php echo LinkPager::widget(['pagination' => $pagination]);?>
<div id="sms-modal" class="modal" tabindex="-1" style="top: auto; left: auto;">
    <div class="modal-dialog modal-lg" style="margin: 0 auto;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h3 class="smaller lighter blue no-margin">短信记录</h3>
            </div>

            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <form id="sendSmsForm">
                            <div class="row">
                                <div class="col-md-9"><input type="text" class="form-control" name="msisdn" placeholder="MSISDN" value="" /></div>
                                <div class="col-md-3"><button type="button" class="btn btn-sm btn-success">导入</button></div>
                            </div>
                            <div class="space-4"></div>
                            <div class="row">
                                <div class="col-md-12"><textarea rows="8" class="form-control" name="content" placeholder="短信内容"></textarea></div>
                            </div>
                            <div class="space-4"></div>
                            <div class="col-md-12"><?php echo Html::radioList('sms_ignore_sign', '', KeyMap::getValues('sms_sign'), ['id' => 'sms_ignore_sign']);?></div>
                            <div class="space-4"></div>
                            <div class="row">
                                <div class="col-md-12"><input type="text" class="form-control" name="remark" placeholder="备注" /></div>
                            </div>
                            <div class="space-4"></div>
                            <div class="row">
                                <div class="col-md-12 text-right"><button type="button" class="btn btn-sm btn-success" onclick="sendSms()">发送</button></div>
                            </div>
                        </form>
                    </div>
                    <div class="col-md-6">
                        <div class="widget-box">
                            <div class="widget-header">
                                <h4 class="widget-title lighter smaller">
                                    <i class="ace-icon fa fa-envelope-o blue"></i>
                                    短信记录
                                </h4>
                            </div>

                            <div class="widget-body">
                                <div id="sms_list" class="widget-main no-padding" style="max-height: 300px; overflow: auto;">
                                </div><!-- /.widget-main -->
                            </div><!-- /.widget-body -->
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-sm btn-danger pull-right" data-dismiss="modal">
                    <i class="ace-icon fa fa-times"></i>
                    关闭
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>

<script>
    /**
     * 刷新卡
     * @param id
     * @param btn 当前按钮
     */
    function refreshCard(id, btn) {
        $(btn).prop('disabled', true).find('i').addClass('fa-spin');
        $.getJSON('<?php echo Url::to(['/user/card/refresh']);?>', {id: id}, function (json) {
            $(btn).prop('disabled', false).find('i').removeClass('fa-spin');
            if (callback(json)) {
                layer.msg('刷新完成。', function () {window.location.reload();});
            }
        });
    }

    /**
     * 强制设备断开网络，使其重新注册。
     */
    function restartCard(id) {
        $.getJSON('<?php echo Url::to(['/user/card/restart']);?>', {id: id}, function (json) {
            if (callback(json)) {
                layer.msg('已发送强制断开网络命令，请稍等。', function () {});
            }
        });
    }

    /**
     * 设置卡状态
     * @param id 卡编号
     * @param status 设置的状态
     */
    function setCardStatus(id, status) {
        if (!confirm('确定要设置卡状态吗？')) {
            return false;
        }
        $.getJSON('<?php echo Url::to(['/user/card/set-card-status']);?>', {id: id, status: status}, function (json) {
            if (callback(json)) {
                layer.msg('设置成功，正在刷新。', function () {refreshCard(id, '');});
            }
        });
    }

    /**
     * 显示短信弹层
     * @param msisdn MSISDN
     */
    function showSms(msisdn,sms_ignore_sign) {
        $('[name=msisdn]').val(msisdn);
        $(":radio[name='sms_ignore_sign'][value='" + sms_ignore_sign + "']").prop("checked", "checked");
        $('#sms_list').html('');
        showSmsList(msisdn);
        $('#sms-modal').modal();
    }

    /**
     * 显示短信列表
     * @param msisdn MSISDN
     */
    function showSmsList(msisdn) {
        $('#sms_list').html('');
        Api.post('/api/sms/list', {msisdn: msisdn}, function (json) {
            json['sms_list'].forEach(function (sms) {
                var html = '';
                if (sms['type'] == 1) {
                    var className = 'default';
                    var statusName = '未发送';
                    switch (sms['status']) {
                        case 1:
                            statusName = '待发送';
                        case 2:
                        case 3:
                            className = 'success';
                            statusName = '提交成功';
                            break;
                        case 4:
                            className = 'warning';
                            statusName = '提交失败';
                            break;
                        case 5:
                            className = 'success';
                            statusName = '发送成功';
                            break;
                        case 6:
                            className = 'danger';
                            statusName = '发送失败';
                    }
                    html += '<p class="alert alert-' + className + '">';
                    html += '<i class="fa fa-arrow-down blue bigger-130"></i>';
                    html += timestampToTime(sms['time']);
                    html += '&nbsp;' + statusName;
                    html += '<br />';
                    html += htmlEncode(sms['content']);
                    html += '</p>';
                }
                if (sms['type'] == 2) {
                    html += '<p class="alert alert-info">';
                    html += '<i class="fa fa-arrow-up blue bigger-130"></i>';
                    html += timestampToTime(sms['time']);
                    html += '<br />';
                    html += htmlEncode(sms['content']);
                    html += '</p>';
                }
                $('#sms_list').append(html);
            });
        });
    }

    /**
     * 时间戳格式化
     * @param timestamp
     */
    function timestampToTime(timestamp) {
        var date = new Date(timestamp * 1000);
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y + M + D + h + m + s;
    }

    /**
     * HTML编码
     */
    function htmlEncode(str) {
        if (str.length === 0) return "";
        var s = str.replace(/&/g, "&gt;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/ /g, "&nbsp;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        s = s.replace(/\n/g, "<br>");
        return s;
    }

    /**
     * 发送短信
     */
    function sendSms() {
        var msisdn = $('#sendSmsForm [name=msisdn]').val();
        var content = $('#sendSmsForm [name=content]').val();
        var sms_ignore_sign = $('input[name="sms_ignore_sign"]:checked').val();
        Api.post('/api/sms/send', {msisdn: msisdn, content: content, sms_ignore_sign: sms_ignore_sign}, function (json) {
            showSmsList(msisdn);
            layer.msg('发送成功。', function () {});
        });
    }
</script>
